<?php

namespace App\Providers;

use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * @var int - MySql 查询计数，调试性能分析用
     */
    protected static $sql_count = 0;

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->logSqlQuery();

        /**
         * 强制 Laravel 使用 HTTPS
         * @see \Illuminate\Routing\UrlGenerator::forceScheme()
         */
//        app('url')->forceScheme('https');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * 测试 log sql 查询语句到 laravel log 文件
     */
    private function logSqlQuery()
    {
        if (! config('app.dump_sql')) return;

        /**
         * @var DatabaseManager $conn
         */
        $conn = app('db');

        /**
         * @see Connection::logQuery()
         */
        $conn->listen(function (QueryExecuted $query) {
            logger($query->sql . ' | ' . $query->time . 'ms');
            logger($query->bindings);
            self::$sql_count++;
        });
    }

    public static function sqlCount(): int
    {
        return self::$sql_count;
    }
}
